package capstoneproject.dudiachi.Main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import capstoneproject.dudiachi.Controller.FestivalManager;
import capstoneproject.dudiachi.Controller.IslandArticleManager;
import capstoneproject.dudiachi.Controller.OldDistrictManager;
import capstoneproject.dudiachi.Controller.PlaceManager;
import capstoneproject.dudiachi.Model.Festival;
import capstoneproject.dudiachi.Model.IslandArticle;
import capstoneproject.dudiachi.Model.OldDistrict;
import capstoneproject.dudiachi.Model.Place;

import com.viewpagerindicator.CirclePageIndicator;

public class SearchResultsActivity extends BaseActivity {

	private TextView txtQuery;
	private Intent i;
	private String tag = "";
	private String query;
	private ArrayList<Bitmap> bitArray;
	private static android.support.v4.app.FragmentManager spfragmentManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_results);
		txtQuery = (TextView) findViewById(R.id.txtQuery);
		spfragmentManager = getSupportFragmentManager();
		i = getIntent();
		if (i != null) {
			tag = i.getStringExtra("tag");
			if (tag != null) {
				searchByTag(tag);
			}
		}

		handleIntent(getIntent());

	}

	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		handleIntent(intent);
	}

	public void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			query = intent.getStringExtra(SearchManager.QUERY);
			SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
					this, MySuggestionProvider.AUTHORITY,
					MySuggestionProvider.MODE);
			suggestions.saveRecentQuery(query, null);
//			suggestions.clearHistory();
			searchByTag(query);
		}
	}

	public void searchByTag(String tag) {
		if (BaseActivity.POS == 0) {
			OldDistrictManager manager = new OldDistrictManager(
					getApplicationContext());
			ArrayList<OldDistrict> list = manager.searchByTag(tag);
			if (list.size() > 0) {
				bitArray = new ArrayList<Bitmap>();

				for (OldDistrict item : list) {
					try {
						bitArray.add(GetBitmapFromAsset.getBitmapFromAssetGV(
								this,
								"Icons/DiaChi/" + item.getOldDistrictIcon()));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				SearchFragment0 fragment = new SearchFragment0();
				Bundle args = new Bundle();
				args.putSerializable("list", list);
				args.putSerializable("bitmap", bitArray);
				fragment.setArguments(args);
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();
				txtQuery.setText("");
			} else {
				txtQuery.setText("Không có kết quả nào !");
			}
		}
		if (BaseActivity.POS == 1) {
			FestivalManager manager = new FestivalManager(
					getApplicationContext());
			ArrayList<Festival> list = manager.searchByTag(tag);
			if (list.size() > 0) {
				bitArray = new ArrayList<Bitmap>();

				for (Festival item : list) {
					try {
						bitArray.add(GetBitmapFromAsset.getBitmapFromAssetGV(
								this, "Icons/LeHoi/" + item.getFestivalIcon()));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				Fragment fragment = new SearchFragment1();
				Bundle args = new Bundle();
				args.putSerializable("list", list);
				args.putSerializable("bitmap", bitArray);
				fragment.setArguments(args);
				android.app.FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();
				txtQuery.setText("");
			} else {
				txtQuery.setText("Không có kết quả nào !");
			}
		}
		if (BaseActivity.POS == 2) {
			PlaceManager manager = new PlaceManager(getApplicationContext());
			ArrayList<Place> list = manager.searchByTag(tag);
			if (list.size() > 0) {
				bitArray = new ArrayList<Bitmap>();

				for (Place item : list) {
					try {
						bitArray.add(GetBitmapFromAsset.getBitmapFromAssetGV(
								this, "Images/DiaDanh/" + item.getImage1()));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				Fragment fragment = new SearchFragment2();
				Bundle args = new Bundle();
				args.putSerializable("list", list);
				args.putSerializable("bitmap", bitArray);
				fragment.setArguments(args);
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();

				txtQuery.setText("");
			} else {
				txtQuery.setText("Không có kết quả nào !");
			}
		}
		if (BaseActivity.POS == 3) {
			IslandArticleManager manager = new IslandArticleManager(
					getApplicationContext());
			ArrayList<IslandArticle> list = manager.searchByTag(tag);
			if (list.size() > 0) {
				bitArray = new ArrayList<Bitmap>();

				for (IslandArticle item : list) {
					try {
						bitArray.add(GetBitmapFromAsset.getBitmapFromAssetGV(
								this, "Images/BienDao/" + item.getImage1()));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				Fragment fragment = new SearchFragment3();
				Bundle args = new Bundle();
				args.putSerializable("list", list);
				args.putSerializable("bitmap", bitArray);
				fragment.setArguments(args);
				android.app.FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();
				txtQuery.setText("");
			} else {
				txtQuery.setText("Không có kết quả nào !");
			}
		}
	}

	public static class SearchFragment0 extends Fragment {

		public SearchFragment0() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_list, container,
					false);
			ArrayList<OldDistrict> list = (ArrayList<OldDistrict>) getArguments()
					.getSerializable("list");
			ArrayList<Bitmap> bitArray = (ArrayList<Bitmap>) getArguments()
					.getSerializable("bitmap");
			ListView listView = (ListView) rootView.findViewById(R.id.list);
			OldDistrictListAdapter adapter = new OldDistrictListAdapter(
					getActivity().getApplicationContext(), list, bitArray);
			adapter.notifyDataSetChanged();
			listView.setAdapter(adapter);
			getActivity().setTitle("Tìm kiếm: Địa Chí Cận Đại");
			return rootView;
		}
	}

	public static class SearchFragment1 extends Fragment {
		private ViewPager mPager;
		private CirclePageIndicator mIndicator;
		private MyAdapter mAdapter;

		public SearchFragment1() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_home, container,
					false);
			ArrayList<Festival> list = (ArrayList<Festival>) getArguments()
					.getSerializable("list");
			ArrayList<Bitmap> bitmap = (ArrayList<Bitmap>) getArguments()
					.getSerializable("bitmap");
			mPager = (ViewPager) rootView.findViewById(R.id.viewPager);
			mIndicator = (CirclePageIndicator) rootView
					.findViewById(R.id.indicator);
			ArrayList<FestivalGridFragment> gridFragments = new ArrayList<FestivalGridFragment>();
			Iterator<Festival> it = list.iterator();

			int i = 0;
			while (it.hasNext()) {
				ArrayList<GridItems> itemList = new ArrayList<GridItems>();
				ArrayList<Bitmap> bitArray = new ArrayList<Bitmap>();

				GridItems item = new GridItems(0, i);

				bitArray.add(bitmap.get(i));

				itemList.add(item);
				i = i + 1;
				it.next();

				for (int j = 1; j <= 8; j++) {
					if (it.hasNext()) {
						GridItems item1 = new GridItems(j, i);
						bitArray.add(bitmap.get(i));
						itemList.add(item1);
						i = i + 1;
						it.next();
					}
				}
				GridItems[] gp = {};
				GridItems[] gridPage = itemList.toArray(gp);
				gridFragments.add(new FestivalGridFragment(gridPage, list,
						bitArray, getActivity()));

			}
			mAdapter = new MyAdapter(spfragmentManager, gridFragments);
			mPager.setAdapter(mAdapter);
			mIndicator.setViewPager(mPager);

			getActivity().setTitle("Tìm kiếm: Địa Danh Tham Quan");
			return rootView;
		}

		private class MyAdapter extends FragmentPagerAdapter {

			private List<FestivalGridFragment> list;

			public MyAdapter(android.support.v4.app.FragmentManager fm,
					List<FestivalGridFragment> list) {
				super(fm);
				this.list = list;
			}

			@Override
			public android.support.v4.app.Fragment getItem(int pos) {
				return this.list.get(pos);
			}

			@Override
			public int getCount() {
				return this.list.size();
			}
		}
	}

	public static class SearchFragment2 extends Fragment {

		private ViewPager mPager;
		private CirclePageIndicator mIndicator;
		private MyAdapter mAdapter;

		public SearchFragment2() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_home, container,
					false);
			ArrayList<Place> list = (ArrayList<Place>) getArguments()
					.getSerializable("list");
			ArrayList<Bitmap> bitmap = (ArrayList<Bitmap>) getArguments()
					.getSerializable("bitmap");

			mPager = (ViewPager) rootView.findViewById(R.id.viewPager);
			mIndicator = (CirclePageIndicator) rootView
					.findViewById(R.id.indicator);
			ArrayList<PlaceGridFragment> gridFragments = new ArrayList<PlaceGridFragment>();
			Iterator<Place> it = list.iterator();

			int i = 0;
			while (it.hasNext()) {
				ArrayList<GridItems> itemList = new ArrayList<GridItems>();
				ArrayList<Bitmap> bitArray = new ArrayList<Bitmap>();

				GridItems item = new GridItems(0, i);

				bitArray.add(bitmap.get(i));

				itemList.add(item);
				i = i + 1;
				it.next();

				for (int j = 1; j <= 8; j++) {
					if (it.hasNext()) {
						GridItems item1 = new GridItems(j, i);
						bitArray.add(bitmap.get(i));
						itemList.add(item1);
						i = i + 1;
						it.next();
					}
				}
				GridItems[] gp = {};
				GridItems[] gridPage = itemList.toArray(gp);
				gridFragments.add(new PlaceGridFragment(gridPage, list,
						bitArray, getActivity()));

			}
			mAdapter = new MyAdapter(spfragmentManager, gridFragments);
			mPager.setAdapter(mAdapter);
			mIndicator.setViewPager(mPager);

			getActivity().setTitle("Tìm kiếm: Địa Danh Tham Quan");
			return rootView;
		}

		private class MyAdapter extends FragmentPagerAdapter {

			private List<PlaceGridFragment> list;

			public MyAdapter(android.support.v4.app.FragmentManager fm,
					List<PlaceGridFragment> list) {
				super(fm);
				this.list = list;
			}

			@Override
			public android.support.v4.app.Fragment getItem(int pos) {
				return this.list.get(pos);
			}

			@Override
			public int getCount() {
				return this.list.size();
			}
		}

	}

	public static class SearchFragment3 extends Fragment {

		public SearchFragment3() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.activity_list, container,
					false);
			ArrayList<IslandArticle> list = (ArrayList<IslandArticle>) getArguments()
					.getSerializable("list");
			ArrayList<Bitmap> bitArray = (ArrayList<Bitmap>) getArguments()
					.getSerializable("bitmap");
			ListView listView = (ListView) rootView.findViewById(R.id.list);
			IslandArticleListAdapter adapter = new IslandArticleListAdapter(
					getActivity().getApplicationContext(), list, bitArray);
			adapter.notifyDataSetChanged();
			listView.setAdapter(adapter);
			getActivity().setTitle("Tìm kiếm: Biển Đảo Thân Thương");
			return rootView;
		}
	}

}
